﻿using System;
using System.Diagnostics;
using System.Reflection;
using System.ServiceModel;
using System.ServiceProcess;
using Autofac.Integration.Wcf;
using NhJump.Persistence.Wcf.Autofac.IoC;

namespace NhJump.Persistence.Wcf.Autofac.Services
{
    public class PersistentServiceHost : ServiceBase
    {
        private ServiceHost _serviceHost;

        public PersistentServiceHost()
        {
            var assembly = Assembly.GetExecutingAssembly();
            var fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
            ServiceName = fvi.ProductName;
        }

        public void ConsoleRun()
        {
            Console.WriteLine("{0}::starting...", ServiceName);

            OnStart(null);

            Console.WriteLine("{0}::ready (ENTER to exit)", ServiceName);
            Console.ReadLine();

            OnStop();

            Console.WriteLine("{0}::stopped", ServiceName);
        }

        protected override void OnStart(string[] args)
        {
            StartTheService();
        }

        private void StartTheService()
        {
            if (_serviceHost != null)
            {
                _serviceHost.Close();
            }

            var bootstrapper = new Bootstrapper();
            AutofacHostFactory.Container = bootstrapper.Container;
            _serviceHost = new ServiceHost(typeof (PersistenceService));
            _serviceHost.AddDependencyInjectionBehavior<IPersistenceService>(bootstrapper.Container);
            _serviceHost.Open();
        }

        protected override void OnStop()
        {
            StopTheService();
        }

        private void StopTheService()
        {
            UnitOfWorkFactory.Unregister(typeof (PersistenceService));

            if (_serviceHost == null) return;
            _serviceHost.Close();
            _serviceHost = null;
        }
    }
}